#!/usr/bin/env bash

set -e

readonly PREFIX=/usr/local/OpenCV

readonly NUM_JOBS=$(nproc)

readonly DEFAULT_VERSION=4.5.4
readonly OPENCV_VERSION=4.5.4

# Jetson Nano
readonly ARCH_BIN=7.2

# Source code directory
readonly OPENCV_SOURCE_DIR=$HOME/Downloads/opencv
readonly OPENCV_BUILD_DIR=$OPENCV_SOURCE_DIR/opencv-$OPENCV_VERSION/build
if [ ! -d "$OPENCV_SOURCE_DIR" ] ; then

	mkdir -p "$OPENCV_SOURCE_DIR"
fi

readonly WHEREAMI=$PWD

PACKAGE_OPENCV="-D CPACK_BINARY_DEB=ON"

cd $OPENCV_SOURCE_DIR

echo "Getting version '$OPENCV_VERSION' of OpenCV"
#git clone --branch "$OPENCV_VERSION" https://github.com/opencv/opencv.git
#git clone --branch "$OPENCV_VERSION" https://github.com/opencv/opencv_contrib.git

# 检查 opencv.zip 是否存在
if [ ! -e opencv.zip ]; then
    wget -O opencv.zip "https://github.com/opencv/opencv/archive/refs/tags/$OPENCV_VERSION.zip"
else
    echo "opencv.zip already exists. Skipping download."
fi

# 检查 opencv_contrib.zip 是否存在
if [ ! -e opencv_contrib.zip ]; then
    wget -O opencv_contrib.zip "https://github.com/opencv/opencv_contrib/archive/refs/tags/$OPENCV_VERSION.zip"
else
    echo "opencv_contrib.zip already exists. Skipping download."
fi

unzip opencv.zip 

unzip opencv_contrib.zip  

readonly CMAKEFLAGS="
	-D CMAKE_BUILD_TYPE=RELEASE
	-D CMAKE_INSTALL_PREFIX=${PREFIX}
          -D BUILD_opencv_world=ON
	-D BUILD_EXAMPLES=OFF
	-D BUILD_opencv_python2=OFF
	-D BUILD_opencv_python3=ON
	-D WITH_FFMPEG=OFF
	-D WITH_TBB=ON
    -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-11.4 
	-D CUDA_FAST_MATH=ON
	-D ENABLE_FAST_MATH=ON
	-D WITH_CUDA=ON
	-D WITH_CUDNN=ON
	-D OPENCV_DNN_CUDA=ON
	-D CUDNN_VERSION='8.4'
	-D CUDA_ARCH_BIN=7.2
    -D CUDA_ARCH_PTX=7.2
	-D WITH_LIBV4L=ON
	-D WITH_V4L=ON
	-D WITH_CUBLAS=ON
	-D OPENCV_ENABLE_NONFREE=ON
	-D OPENCV_EXTRA_MODULES_PATH=$OPENCV_SOURCE_DIR/opencv_contrib-$OPENCV_VERSION/modules
	-D OPENCV_PYTHON3_INSTALL_PATH=/home/admin-nx/.local/lib/python3.8/site-packages 
	-D PYTHON_EXECUTABLE=/usr/bin/python3.8 
	-D OPENCV_GENERATE_PKGCONFIG=ON
	-D OPENCV_PC_FILE_NAME=opencv.pc
	-D WITH_GSTREAMER=OFF
	-D WITH_GSTREAMER_0_10=OFF
	-D WITH_OPENGL=ON
    -D ENABLE_NEON=ON 
    -D WITH_CAROTENE=ON
	-D CPACK_BINARY_DEB=OFF
	-D BUILD_PERF_TESTS=OFF
	-D BUILD_TESTS=OFF
	-D INSTALL_PYTHON_EXAMPLES=OFF
	-D INSTALL_C_EXAMPLES=OFF	
	"

echo "cmake flags: ${CMAKEFLAGS}"

if [ ! -d "$OPENCV_BUILD_DIR" ] ; then

	        mkdir -p "$OPENCV_BUILD_DIR"
fi


cd $OPENCV_BUILD_DIR

time cmake ${CMAKEFLAGS} ..

#start the build
time make -j$NUM_JOBS

#make test
sudo make install

cd $WHEREAMI
